#!/bin/bash

### BEGIN INIT INFO
# Provides:          firstrun
# Required-Start:    $all
# Required-Stop:
# Should-Start:      armhwinfo
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Armbian first run tasks
# Description:       Something needs to be done when is
#                    starting at first time.
### END INIT INFO

. /etc/armbian-release
. /etc/os-release
. /lib/init/vars.sh
. /lib/lsb/init-functions

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Log=/var/log/armhwinfo.log

case "$1" in
	start)

	# Run a q&d benchmark to be able to identify cards way too slow easily
	echo -e "\n### quick iozone test:$(cd /root; iozone -e -I -a -s 1M -r 4k -i 0 -i 1 -i 2 | grep '^            1024' | sed 's/            1024      //')" >> $Log

	# workaround for AP6212a under mainline kernel
	#if [ -n "$(lsmod | grep brcmfmac)" ] && [ -z "$(dmesg | grep brcmf | grep Firm)" ]; then
	#	cp /lib/firmware/brcm/brcmfmac43430-sdio.bin /lib/firmware/brcm/brcmfmac43430-sdio.bin.bak
	#	cp /lib/firmware/ap6212/fw_bcm43438a1.bin /lib/firmware/brcm/brcmfmac43430-sdio.bin
	#	rmmod brcmfmac
	#	modprobe brcmfmac
	#fi

	# BT tweaks
	case ${BOARD} in
		cubietruck)
			systemctl enable brcm40183-patch && service brcm40183-patch start
			;;
      bananapim2zero|bananapim2plus|nanopiair|nanopim1plus|orangepizeroplus2*|orangepiwin|nanopineoplus2|nanopik2)
			update-rc.d ap6212-bluetooth defaults
			;;
		cubox-i)
			update-rc.d brcm4330-patch defaults && /etc/init.d/brcm4330-patch start
			;;
	esac

	# update console info
	setupcon --save

	# add unique installation id to the image release file
	cat /proc/sys/kernel/random/uuid >> /etc/armbian-image-release

	# SSH Keys creation
	rm -f /etc/ssh/ssh_host*
	read entropy_before </proc/sys/kernel/random/entropy_avail
	dpkg-reconfigure openssh-server >/dev/null 2>&1
	service sshd restart
	read entropy_after </proc/sys/kernel/random/entropy_avail
	echo -e "\n### [firstrun] Recreated SSH keys (entropy: ${entropy_before} ${entropy_after})" >>${Log}

	# set up swap preferring zram if available over swapfile
	dpkg -l | grep -q 'zram-config'
	case $? in
		0)
			echo -e "\n### [firstrun] Skipped swapfile creation since zram is available" >>${Log}
			;;
		*)
			FREESIZE=$(( $(findmnt --target / -n -o AVAIL -b) / 1048576 )) # MiB
			SWAPFILE=/var/swap
			if [[ ! -f $SWAPFILE && $FREESIZE -gt 132 ]]; then
				fallocate -l 128M $SWAPFILE || dd if=/dev/zero of=$SWAPFILE bs=1M count=128 status=noxfer
				chown root:root $SWAPFILE
				chmod 0600 $SWAPFILE
				mkswap $SWAPFILE
				swapon $SWAPFILE
				grep -q swap /etc/fstab || echo "$SWAPFILE none swap sw 0 0" >> /etc/fstab
				echo -e "\n### [firstrun] Created 128MB emergency swap as $SWAPFILE" >>${Log}
			fi
			# set vm.swappiness to 0 (even with a btrfs rootfs)
			grep -q 'vm.swappiness' /etc/sysctl.conf || echo "vm.swappiness=0" >> /etc/sysctl.conf
			;;
	esac

	# get rid of purple background color in newt apps whiptail, partimage, debconf ... Reverting to Debian look.
	sed -e 's/magenta/blue/g' -i /etc/newt/palette

	# desktop tweaks - enable show windows content on stronger boards
	cpu_cores=$(grep -c '^processor' /proc/cpuinfo | sed 's/^0$/1/')
	if [[ ${cpu_cores} -gt 2 && -f /etc/skel/.config/xfce4/xfconf/xfce-perchannel-xml/xfwm4.xml ]]; then
		sed -i 's/<property name="box_move" type="bool" value=".*/<property name="box_move" type="bool" value="false"\/>/g' \
		/etc/skel/.config/xfce4/xfconf/xfce-perchannel-xml/xfwm4.xml
	fi

	# some hardware workarounds
	case $LINUXFAMILY in
		sun7i|sun8i)
			# set some mac address for BT
			[[ -n $(lsmod | egrep "dhd|brcmfmac" ) ]] && \
				(MACADDR=$(printf '43:29:B1:%02X:%02X:%02X\n' $[RANDOM%256] $[RANDOM%256] $[RANDOM%256]) ; \
				sed -i "s/^MAC_ADDR=.*/MAC_ADDR=${MACADDR}/" /etc/default/brcm40183 ;\
				sed -i "s/^MAC_ADDR=.*/MAC_ADDR=${MACADDR}/" /etc/default/ap6212 \
				echo -e "\n### [firstrun] Use MAC address ${MACADDR} for Bluetooth from now" >>${Log})

			case $BOARD_NAME in
				"NanoPi Air"|"NanoPi M1 Plus"|"Nanopi Neo Plus 2")
					# change serial port for BT on FriendlyELEC H3 boards
					sed -i "s/^PORT=.*/PORT=ttyS3/" /etc/default/ap6212
					;;
				"Orange Pi Lite"|"Orange Pi Zero Plus 2"|"NanoPi Air"|"Orange Pi R1")
					# relink /etc/network/interfaces on Wi-Fi only boards
					cd /etc/network/ && ln -sf interfaces.network-manager interfaces
					;;
				"Orange Pi Zero"|"NanoPi Duo"|"Sunvell R69")
					# set XR819 WiFi address permanently based on a random address using Allwinner's MAC prefix
					MACADDR=$(printf 'DC:44:6D:%02X:%02X:%02X\n' $[RANDOM%256] $[RANDOM%256] $[RANDOM%256])
			                echo "options xradio_wlan macaddr=${MACADDR}" >/etc/modprobe.d/xradio_wlan.conf
			                echo -e "\n### [firstrun] Use MAC address ${MACADDR} for Wi-Fi from now" >>${Log}
					cd /etc/network/ && ln -sf interfaces.network-manager interfaces
					(modprobe -r xradio_wlan && sleep 1 && modprobe xradio_wlan) &
					;;
			esac

			# trigger red or blue LED as user feedback
			echo heartbeat >/sys/class/leds/*red*/trigger 2>/dev/null || echo heartbeat >/sys/class/leds/*blue*/trigger 2>/dev/null
			;;
		rockchip|nanopim3)
			# set MAC for eth0
			MACADDR=$(printf 'da:42:ea:%02X:%02X:%02X\n' $[RANDOM%256] $[RANDOM%256] $[RANDOM%256])
			sed -i "s/^\#[^ tab]\+hwaddress ether/\thwaddress ether $MACADDR/" /etc/network/interfaces
			;;
		mvebu64)
			# configure/enable/start systemd-networkd
			systemctl start systemd-networkd.service
			systemctl start systemd-resolved.service
			systemctl enable systemd-networkd.service
			systemctl enable systemd-resolved.service
			ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf
			systemctl restart systemd-networkd
			;;
	esac

	systemctl disable firstrun
	exit 0
	;;

	*)
	echo "Usage: $0 start"
	exit 0
	;;
esac
